<script setup>
	import {
		ref,
		watch,
		watchEffect
	} from 'vue'

	const question = ref('')
	const answer = ref('Questions usually contain a question mark. ;-)')
	const loading = ref(false)

	// 可以直接侦听一个 ref
	watch(question, async (newQuestion, oldQuestion) => {
		if (newQuestion.includes('?')) {
			loading.value = true
			answer.value = 'Thinking...'
			try {
				const res = await fetch('https://yesno.wtf/api')
				answer.value = (await res.json()).answer
			} catch (error) {
				answer.value = 'Error! Could not reach the API. ' + error
			} finally {
				loading.value = false
			}
		}
	})

	const todoId = ref(1)
	const data = ref('')

	// watch(
	// 	todoId,
	// 	async () => {
	// 		const response = await fetch(
	// 			`https://jsonplaceholder.typicode.com/todos/${todoId.value}`
	// 		)
	// 		// data.value = (await response.json()).title
	// 		data.value = JSON.stringify(await response.json())
	// 	}, {
	// 		immediate: true
	// 	}
	// )  //可以用watchEffect替代
	watchEffect(async () => {
	  const response = await fetch(
	    `https://jsonplaceholder.typicode.com/todos/${todoId.value}`
	  )
	  data.value = JSON.stringify(await response.json())
	})
</script>

<template>
	<p>
		Ask a yes/no question:
		<input v-model="question" :disabled="loading" />
	</p>
	<p>{{ answer }}</p>

	<p>{{todoId}}={{data}}</p>
	<button type="button" @click="todoId++">todoId = {{todoId}}</button>
</template>